package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 1.准备request
        SearchRequest request = new SearchRequest("app_info_article");

        // 2.准备DSL
        // 设置查询条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 判断是否有关键字
        if (StringUtils.isBlank(dto.getSearchWords())) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            // 根据字段分词查询
            boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR)); //分词后词条的关系

            // 异步保存搜索记录
            ApUser user = AppThreadLocalUtil.getUser();
            if (user != null && dto.getFromIndex() == 0){
                // 用户登录了才保存,游客登录不保存
                apUserSearchService.insert(dto.getSearchWords(),user.getId());
            }
        }

            // 时间范围
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

            // 添加条件
            request.source().query(boolQuery);

            // 设置分页
            request.source().from(0).size(dto.getPageSize());

            // 按照时间倒序排列
            request.source().sort("publishTime", SortOrder.DESC);

            // 高亮展示
            request.source().highlighter(new HighlightBuilder()
                    .field("title")
                    .preTags("<font style='color: red; font-size: inherit;'>")
                    .postTags("</font>"));

        // 3.发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        // 4.解析返回结果
        ArrayList<Map> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);

            // 获取高亮数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            // 判断高亮数据是否存在
            if (highlightFields != null && highlightFields.size() > 0){
                HighlightField highlightField = highlightFields.get("title");
                Text[] texts = highlightField.getFragments();
                String highLightTitle = StringUtils.join(texts);
                map.put("h_title",highLightTitle);
            }else {
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
